package org.nutz.mvc.view;

import org.nutz.mvc.Mvcs;
import org.nutz.mvc.View;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.WebContext;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * Created with IntelliJ IDEA.
 *
 * @author: 薄成文 13-9-12 下午11:26
 * To change this template use File | Settings | File Templates.
 */
public class ThymeleafView implements View {
    private TemplateEngine templateEngine;
    private String view;

    public ThymeleafView(TemplateEngine templateEngine, String view) {
        this.templateEngine = templateEngine;
        this.view = view;
    }

    @Override
    public void render(HttpServletRequest req, HttpServletResponse resp, Object obj) throws Throwable {
        resp.setContentType("text/html; charset=utf-8");
        resp.setHeader("Pragma", "no-cache");
        resp.setHeader("Cache-Control", "no-cache");
        resp.setDateHeader("Expires", 0);


        //WebContext context = new WebContext(req, resp, req.getServletContext(), req.getLocale());
        WebContext context = new WebContext(req, resp, Mvcs.getServletContext(), req.getLocale());
//        for (Enumeration<String> attrs=request.getAttributeNames(); attrs.hasMoreElements();) {
//            String attrName = attrs.nextElement();
//            context.setVariable(attrName, request.getAttribute(attrName));
//        }

        PrintWriter writer = null;
        try {
            writer = resp.getWriter();
            templateEngine.process(view, context, writer);
        } catch (Exception e) {
            throw e;
        } finally {
            if (writer != null)
                writer.close();
        }
    }
}
